package geoapi

import (
	"encoding/json"
	"errors"
)

// ipAPIResp
type ipAPIResp struct {
	Status      string `json:"status"`
	Message     string `json:"message"`
	Country     string `json:"country"`
	CountryCode string `json:"countryCode"`
	RegionName  string `json:"regionName"`
	City        string `json:"city"`
	Isp         string `json:"isp"`
}

// GeoIPAPI 请求 http://ip-api.com/json/ api
// http://ip-api.com/json/xx.xx.xx.xx
func GeoIPAPI(host string) (ig IPGeo, err error) {
	uri := `http://ip-api.com/json/` + host
	data, err := getApiData(uri)
	if err != nil {
		return
	}
	var t ipAPIResp
	err = json.Unmarshal(data, &t)
	if err != nil {
		return
	}
	if t.Status != "success" {
		if t.Message != "" {
			err = errors.New(t.Message)
		} else {
			err = errors.New("invalid query")
		}
		return
	}
	ig.City = t.City
	ig.CountryCode = t.CountryCode
	ig.CountryName = t.Country
	ig.Isp = t.Isp
	ig.Query = host
	ig.StateProv = t.RegionName
	ig.Status = "success"
	return
}
